package com.codehacker.job.mallservice.controller;

import com.codehacker.job.mallservice.dao.CartMapper;
import com.codehacker.job.mallservice.dto.ResponseDTO;
import com.codehacker.job.mallservice.entity.Cart;
import com.codehacker.job.mallservice.entity.CartExample;
import java.util.Date;
import javax.annotation.Resource;

import com.codehacker.job.mallservice.entity.Goods;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author zhuyuwei
 * @date 2017/7/27
 * @description:
 */
@Controller
@RequestMapping("/api/cart")
public class CartController {

    @Resource
    private CartMapper cartMapper;

    @GetMapping("/{uid}")
    @ResponseBody
    public ResponseDTO<Cart> findByUserId(@PathVariable("uid") Integer uid) {
        ResponseDTO<Cart> result = new ResponseDTO<Cart>();
        CartExample example = new CartExample();
        example.createCriteria().andUserIdEqualTo(uid);
        result.getData().getItems().addAll(cartMapper.selectByExample(example));
        result.getMeta().setCode(0);
        return result;
    }

    @PostMapping("/add")
    @ResponseBody
    public ResponseDTO<Cart> add(@RequestBody Goods goods, @RequestParam("userId") Integer userId) {
        ResponseDTO<Cart> result = new ResponseDTO<Cart>();
        Cart cart = new Cart();
        cart.setGoodId(goods.getId());
        cart.setUserId(userId);
        cart.setCreateTime(new Date());
        cart.setUpdateTime(new Date());
        cartMapper.insertSelective(cart);
        result.getMeta().setCode(0);
        return result;
    }

    @DeleteMapping("/del")
    @ResponseBody
    public ResponseDTO<Cart> del(@RequestParam("id") Integer id) {
        ResponseDTO<Cart> result = new ResponseDTO<Cart>();
        result.getMeta().setCode(0);
        cartMapper.deleteByPrimaryKey(id);
        return result;
    }

    @PostMapping("/clear")
    @ResponseBody
    public ResponseDTO<Cart> clear(@RequestParam("userId") Integer userId) {
        ResponseDTO<Cart> result = new ResponseDTO<Cart>();
        CartExample example = new CartExample();
        example.createCriteria().andUserIdEqualTo(userId);
        cartMapper.deleteByExample(example);
        result.getMeta().setCode(0);
        return result;
    }
}
